package fr.emse.tatiana.corpus;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.draw2d.ToggleButton;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import fr.emse.tatiana.CorpusNavigationView;



/**
 * Wizard class
 */

public class AddFileWizard extends Wizard implements INewWizard

{
	// wizard pages
	AddFileMainPage choosefile;
	AddFileSynchroPage synchronisefile; 
	//PlanePage planePage;

	// the model
	CorpusFile cf;


	protected Corpus corpus;

	/**1
	 * Constructor for HolidayMainWizard.
	 */
	public AddFileWizard() {
		super();	
	}

	@Override
	public void addPages() {
		choosefile = new AddFileMainPage(corpus);
		addPage(choosefile);
		synchronisefile = new AddFileSynchroPage("");
		addPage(synchronisefile);
	}



	/**
	 * @param selection is assumed to be null. The selection is fetched from the navigaiton view
	 * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		corpus = ((CorpusNavigationView) workbench.getActiveWorkbenchWindow().getActivePage().findView(CorpusNavigationView.ID)).getSelectedCorpus();
		if (corpus == null) {
			return;
		}
	}
	

	@Override
	public boolean performFinish() {
		IFolder traces = corpus.getProject().getFolder("traces");
	    IFile newFile = traces.getFile(cf.getName());
	    try {
	    	traces.refreshLocal(IResource.DEPTH_INFINITE, null);
	    	if (!traces.exists()) {
	    		traces.create(false, true, null);
	    	}
	    	newFile.refreshLocal(IResource.DEPTH_ZERO, null);
	    	if (!newFile.exists()) {
	    		FileInputStream fileStream = new FileInputStream(cf.getPath());
	    		// TODO soon add monitor
	    		newFile.create(fileStream, false, null);
	    		newFile.refreshLocal(IResource.DEPTH_ZERO, null);
	    	}
			cf.setFile(newFile);
			cf.save();
			
		} catch (CoreException e) {
			MessageDialog.openError(getShell(), "Add File to Corpus", "Could not add this file to the corpus");
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// not very likely - just found it in a file system
			e.printStackTrace();
		}
		return true;
	}
}
